#include <SoftwareSerial.h>

const byte rxPin = 9;
const byte txPin = 8;

SoftwareSerial mySerial (rxPin, txPin);

int Init_Finish=0;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);  
  Serial.println("hello esp8266 begin");
  // define pin modes for tx, rx:
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  //delay(10000);
  Serial.println("wifi init");  
  WifiInit();
}

//封装http包并发送到oneNet平台
void SendDataToYun(float temp) 
{
 
  static int cnt = 0;   //JSON格式数据包长度
 
  SendCmd("AT+CIPMODE=1\r");//开启透传模式
  delay(2000); 
  SendCmd("AT+CIPSEND\r");//开始透传数据
  delay(2000); 
 
  //http报头字符串
  String cmd("POST /devices/70290/datapoints HTTP/1.1\r\n"
              "User-Agent: curl/7.35.0\r\n"
              "Host: api.heclouds.com\r\n"
              "Accept: */*\r\n"
              "api-key:B4ZGKmtaL5eJw6NIpjEEI+kULqQ=\r\n"  //API key，从oneNet获取
              "Content-Length:" + String(cnt) + "\r\n"   //JSON格式数据长度
              "Content-Type: application/x-www-form-urlencoded\r\n"
              "\r\n");
 
  SendCmd(cmd); 
 
  //JSON格式数据封装
  cnt = Serial.print("{\"datastreams\":["
                      "{\"id\":\"temp\",\"datapoints\":[{\"value\":" + String(temp) + "}]},"
                      "{\"id\":\"hum\",\"datapoints\":[{\"value\":" + String(hum) + "}]},"
                      "{\"id\":\"light\",\"datapoints\":[{\"value\":" + String(light) + "}]},"
                      "{\"id\":\"noise\",\"datapoints\":[{\"value\":" + String(niose) + "}]}"
  Serial.println();  //向服务器发送数据
 
  while (1)//等待服务器返回结果
  {
      if (Serial.available()> 0 && Serial.find("error") == true)//判断返回结果
      {
          //LedFlash();
          Serial.println("+++" ); //结束数据透传
          break;
      }
  }
 
  delay(1000); 
  while (1)
  {
      Serial.println("AT+CIPSTATUS\r"); //查看与服务器连接状态
      if (Serial.available()> 0 && Serial.find("TCP") == true)//TCP连接未中断转入下一次传输
      {
          //LedFlash();
          break;
      }
      else //TCP连接中断，重新与服务器建立TCP连接
      {
          SendCmd("AT+CIPSTART=\"TCP\",\"183.230.40.33\",80\r");
      }
  }
}


void WifiInit(void)
{
  SendCmd("AT+CWMODE=3\r");//设置为softAP+station共存模式
  delay(5000);
  SendCmd("AT+RST\r");//重启WIFI生效
  delay(50000);
  SendCmd("AT+CWJAP=\"HiWiFi_BaoBao\",\"198291dylhdylh\"\r");//连接无线网络
  delay(5000);
  SendCmd("AT+CIFSR\r");//返回设备的IP地址
  delay(5000);
  SendCmd("AT+CIPSTART=\"TCP\",\"192.168.199.128\",8234\r");//和目标服务器建立TCP连接
  delay(8000);
  SendCmd("AT+CIPMODE=1\r");//开启透传模式
  delay(5000);
  SendCmd("AT+CIPSEND\r");//开始透传
  delay(5000);
  SendCmd("hello world");
}

void SendCmd(String data)
{
  mySerial.println(data);  //发送AT指令 
}


void loop() {
  while(mySerial.available()>0) 
  {
      Serial.write(mySerial.read());  
  }
   SendCmd("hello world");
   delay(500);
}
